﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using AutoMapper.Internal.Mappers;
using BW.WMS.BasicData_LC.Dto.Input;
using BW.WMS.BasicData_LC.Dto.OutPut;
using BW.WMS.CodeEnum;
using BW.WMS.LC.Dto.OutPut;
using BW.WMS.Model;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;

namespace BW.WMS.BasicData_LC
{
    /// <summary>
    /// 库位接口实现
    /// </summary>
    public class LocationAppService : ApplicationService, ILocationAppService
    {
        private readonly IRepository<Dm_Librarylocation,Guid> _locationRepository;
        private readonly IRepository<Me_PurchaseHd, Guid> _PurchaseHdRepository;
        private readonly IRepository<Dm_Code, Guid> _codeRepository;
        private readonly IRepository<Dm_Warehouser, Guid>  _warehouserRepository;

        public LocationAppService(IRepository<Dm_Librarylocation, Guid> locationRepository, 
            IRepository<Me_PurchaseHd, Guid> purchaseHdRepository, 
            IRepository<Dm_Code, Guid> codeRepository,
            IRepository<Dm_Warehouser, Guid> warehouserRepository)
        {
            _locationRepository = locationRepository;
            _PurchaseHdRepository = purchaseHdRepository;
            _codeRepository = codeRepository;
            _warehouserRepository = warehouserRepository;
        }






        /// <summary>
        /// 新增库位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> AddLocation(List<AddUpdateLibrarylocationInput> input)
        {
            foreach (var item in input) { 
            item.Id = Guid.NewGuid();
            }
            var result=new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "新增库位成功";



            var li=ObjectMapper.Map<List<AddUpdateLibrarylocationInput>,List<Dm_Librarylocation>>(input);
              await _locationRepository.InsertManyAsync(li);

            result.Data = 1;

            return result;
        }
        /// <summary>
        /// 进货单显示
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<Me_PurchaseHdDto>>> GetMe_PurchaseDtl()
        {
            var result = new ApiResult<List<Me_PurchaseHdDto>>();
            // 获取所有进货单数据
            var query = await _PurchaseHdRepository.GetQueryableAsync();
            var purchaseList = query.OrderByDescending(p => p.CreationTime).ToList();

            // 使用ObjectMapper将实体映射为DTO
            var purchaseDtos = ObjectMapper.Map<List<Me_PurchaseHd>, List<Me_PurchaseHdDto>>(purchaseList);

            result.Code = ApiEnum.Success;
            result.Message = "获取进货单列表成功";
            result.Data = purchaseDtos;
            return result;
        }
        /// <summary>
        /// 进货单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddMe_PurchaseHd(AddMe_PurchaseHdInput input)
        {
            var result = new ApiResult<int>();
            input.Id = Guid.NewGuid();
            // 使用ObjectMapper将DTO映射为实体
            var purchaseHd = ObjectMapper.Map<AddMe_PurchaseHdInput, Me_PurchaseHd>(input);

            // 如果没有指定进货日期，则使用当前时间
            if (string.IsNullOrEmpty(purchaseHd.Purdate))
            {
                purchaseHd.Purdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }

            // 添加到仓库
            var addedPurchaseHd = await _PurchaseHdRepository.InsertAsync(purchaseHd);

            if (addedPurchaseHd != null)
            {
                result.Code = ApiEnum.Success;
                result.Message = "创建进货单成功";
                result.Data = 1;
            }
            else
            {
                result.Code = ApiEnum.Error;
                result.Message = "创建进货单失败";
                result.Data = -1;
            }
            return result;
        }

        /// <summary>
        /// 删除库位
        /// </summary>
        /// <param name="id">库位编号集合</param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteLocation(List<string> id)
        {
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "删除成功";

            // 获取所有需要删除的库位实体
            var list = await _locationRepository.GetListAsync(a => id.Contains(a.Librarylocationid));

            // 批量删除
            await _locationRepository.DeleteManyAsync(list);

            result.Data = list.Count; // 返回删除的数量
            return result;
        }

        /// <summary>
        /// 获取库位列表
        /// </summary>
        /// <param name="ouput"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiPaging<LibrarylocationDto>> GetLocationList(LibrarylocationOuput ouput)
        {
            var query=await _locationRepository.GetQueryableAsync();

            var totalcount=query.Count();
            var totalpage= (int) Math.Ceiling(totalcount / (double) ouput.pagesize);
            var list=query.OrderByDescending(a=>a.CreationTime).Skip((ouput.pageindex - 1) * ouput.pagesize).Take(ouput.pagesize).ToList();

            var result = new ApiPaging<LibrarylocationDto>()
            {
                TotalCount = totalcount,
                TotalPages = totalpage,
                PageData = ObjectMapper.Map<List<Dm_Librarylocation>, List<LibrarylocationDto>>(list)
            };

            return result;
        }


        /// <summary>
        /// 修改库位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> UpdateLocation(AddUpdateLibrarylocationInput input)
        {
            var result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "修改库位成功";

            var li = ObjectMapper.Map<AddUpdateLibrarylocationInput, Dm_Librarylocation>(input);

            var a = await _locationRepository.UpdateAsync(li);

            result.Data = 1;

            if (a == null)
            {
                result.Code = ApiEnum.Error;
                result.Message = "修改失败";
                result.Data = -1;
            }
            return result;
        }
        /// <summary>
        /// 库位下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<LibrarylocationDto>>> GetLibraryLocation()
        {
            var result = new ApiResult<List<LibrarylocationDto>>();

            try
            {
                var departmentsQuery = await _locationRepository.GetQueryableAsync();

                var departmentsList = departmentsQuery.ToList();

                var dtos = ObjectMapper.Map<List<Dm_Librarylocation>, List<LibrarylocationDto>>(departmentsList);

                return new ApiResult<List<LibrarylocationDto>>
                {
                    Code = ApiEnum.Success,
                    Message = "获取库位下拉框列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "获取库位下拉框列表时出错");
                result.Code = ApiEnum.Error;
                result.Message = $"获取库位下拉框列表出错: {ex.Message}";
            }

            return result;
        }
        /// <summary>
        /// 仓库下拉框
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<WareHouseDto>>> GetWarehouse()
        {
            var result = new ApiResult<List<WareHouseDto>>();

            try
            {
                var departmentsQuery = await _warehouserRepository.GetQueryableAsync();

                var departmentsList = departmentsQuery.ToList();

                var dtos = ObjectMapper.Map<List<Dm_Warehouser>, List<WareHouseDto>>(departmentsList);

                return new ApiResult<List<WareHouseDto>>
                {
                    Code = ApiEnum.Success,
                    Message = "获取仓库下拉框列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "获取仓库下拉框列表时出错");
                result.Code = ApiEnum.Error;
                result.Message = $"获取仓库下拉框列表出错: {ex.Message}";
            }
            return result;
        }
        /// <summary>
        /// 出入库类型
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult<List<CodeDto>>> GetCodeList()
        {
            var result = new ApiResult<List<CodeDto>>();

            try
            {
                var departmentsQuery = await _codeRepository.GetQueryableAsync();

                var departmentsList = departmentsQuery.ToList();
                
                
                var dtos = ObjectMapper.Map<List<Dm_Code>, List<CodeDto>>(departmentsList);

                return new ApiResult<List<CodeDto>>
                {
                    Code = ApiEnum.Success,
                    Message = "获取仓库下拉框列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "获取仓库下拉框列表时出错");
                result.Code = ApiEnum.Error;
                result.Message = $"获取仓库下拉框列表出错: {ex.Message}";
            }

            return result;
        }
    }
}
